package com.service;

import com.bean.LoginCreds;
import com.bean.other.MetaInfo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mapper.LoginCredsMapper;
import com.mapper.repository.LoginCredsRepository;
import com.service.impl.LoginCredsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

@Service
public class LoginCredsServiceImpl implements LoginCredsService {

    @Autowired
    private LoginCredsRepository loginCredsRepository;

    @Autowired
    private LoginCredsMapper loginCredsMapper;

    @Override
    public String insert(LoginCreds loginCreds) {
        loginCreds.setId(UUID.randomUUID().toString());
        if(loginCreds.getBelong()!=null){
            String belongs =String.join(",",loginCreds.getBelong());
            loginCreds.setBelongs(belongs);
        }
        loginCreds.setCreatetime(LocalDateTime.now());
        loginCredsRepository.save(loginCreds);
        return "新增成功";
    }

    @Override
    public String update(LoginCreds loginCreds) {
        loginCreds.setUpdatetime(LocalDateTime.now());
        if(loginCreds.getBelong()!=null){
            String belongs =String.join(",",loginCreds.getBelong());
            loginCreds.setBelongs(belongs);
        }
        loginCredsRepository.save(loginCreds);
        return "更新成功";
    }

    @Override
    public String delete(LoginCreds loginCreds) {
        loginCredsRepository.delete(loginCreds);
        return "删除成功";
    }

    @Override
    public PageInfo<LoginCreds> select(LoginCreds loginCreds, MetaInfo metaInfo) {
        //PageHelper.startPage(metaInfo.getPage(),metaInfo.getSize());
        PageHelper.startPage(metaInfo.getPage(),metaInfo.getSize(),"createtime");
        List<LoginCreds> list=loginCredsMapper.selectLike(loginCreds);
        PageInfo<LoginCreds> pageInfo=new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public LoginCreds get(String id) {
        Optional<LoginCreds> optional=loginCredsRepository.findById(id);
        if(optional.isPresent()){
            return optional.get();
        }
        return null;
    }
}
